import Vue from 'vue'
import VueRouter from 'vue-router'
import {getToken} from '../utils/storage'
// import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/Detail/:id',
    name: 'Detail',
    component: ()=>import('../views/Detail.vue')
      },
  {
    path: '/login',
    name: 'Login',
    component: ()=>import('../views/Login.vue') //懒加载
  },
  {
    path: '/register',
    name: 'register',
    component: ()=>import('../views/Register.vue')
  },
  {
    path: '/',
    name: 'Layout',
    redirect:'/article',
    component: ()=>import('../views/Layout.vue'),
    children:[
      {
        path: '/article',
        name: 'Article',
        component: ()=>import('../views/Article.vue')
      },
      {
        path: '/collect',
        name: 'Collect',
        component: ()=>import('../views/Collect.vue')
      },
      {
        path: '/like',
        name: 'Like',
        component: ()=>import('../views/Like.vue')
      },
      {
        path: '/my',
        name: 'My',
        component: ()=>import('../views/My.vue')
      },
      
    ]
  }
  // {
  //   path: '/about',
  //   name: 'About',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   /*  */
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')//路由懒加载
  // }
]

const router = new VueRouter({
  routes
})

const whiteList = ['/login', '/register'] // 白名单列表，记录无需权限访问的所有页面

router.beforeEach((to, from, next) => {
  const token = getToken()
  // 如果有token，直接放行
  if (token) {
    next()
  } else {
    // 没有token的人, 看看你要去哪
    // (1) 访问的是无需授权的页面（白名单），也是放行
    //     就是判断，访问的地址，是否在白名单数组中存在 includes
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // (2) 否则拦截到登录
      next('/login')
    }
  }
})

const originalPush = VueRouter.prototype.push;
const originalReplace = VueRouter.prototype.replace;
//push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch(err => err);
};
//replace
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
    if (onResolve || onReject)
        return originalReplace.call(this, location, onResolve, onReject);
    return originalReplace.call(this, location).catch(err => err);
};



export default router
